<?php

/**
 *    Desc
 *
 *    @author    Garbin
 *    @usage    none
 */
class DefaultApp extends MemberbaseApp
{
    function __construct()
    {
        $this->DefaultApp();
    }
    function DefaultApp()
    {
        parent::__construct();
		/*$user = $this->visitor->get();
		$user_mod =& m('member');
		if (!$user_mod->check_powers($user['user_id'], USER_ADMIN)) {
			$this->show_warning('no_powers_to_visit');
			exit;
		};
		$this->_buyer_mod =& m('buyer');*/
        $this->_curitem(APP);
    }
    function index()
    {
		//判断是否工厂用户
		$is_factory=$this->visitor->get("is_factory");
		$this->assign('is_factory', $is_factory);
		$this->assign('user',$this->visitor->get());
        $this->display('index.html');
    }
    
    //去注册页面的缓冲页
    function go_register(){
    	$this->display('register.go.html');
    }
    
    
    /**
     *    注册一个新用户
     *
     *    @author    Garbin
     *    @return    void
     */
    function register()
    {
    	if ($this->visitor->has_login)
    	{
    		$this->show_warning('has_login');
    
    		return;
    	}
    	if (!IS_POST)
    	{
    		if (!empty($_GET['ret_url']))
    		{
    			$ret_url = trim($_GET['ret_url']);
    		}
    		else
    		{
    			if (isset($_SERVER['HTTP_REFERER']))
    			{
    				$ret_url = $_SERVER['HTTP_REFERER'];
    			}
    			else
    			{
    				$ret_url = SITE_URL . '/index.php';
    			}
    		}
    		$this->assign('ret_url', rawurlencode($ret_url));
    		$this->_curlocal(LANG::get('user_register'));
    		$this->assign('page_title', Lang::get('user_register') . ' - ' . Conf::get('site_title'));
    		$region_mod=& m('region');
    		$this->assign('regions',$region_mod->get_options(0));
//     		if (Conf::get('captcha_status.register'))
//     		{
//     			$this->assign('captcha', 1);
//     		}
    
    		/* 导入jQuery的表单验证插件 */
    		//$this->import_resource('jquery.plugins/jquery.validate.js');
    		$this->display('register.html');
    	}
    	else
    	{
//     		if (!$_POST['agree'])
//     		{
//     			$this->show_warning('agree_first');
    
//     			return;
//     		}
    		if ($_POST['password'] != $_POST['confirm_password'])
    		{
    			/* 两次输入的密码不一致 */
    			$this->show_warning('password_inconsistent');
    			return;
    		}
    
    		/* 注册并登陆 */
    		$user_name = trim($_POST['user_name']);
    		$password  = $_POST['password'];
    		$email     = trim($_POST['email']);
    		$phone_mob = trim($_POST['phone_mob']);
    		$address   = trim($_POST['address']);
    		$local_data=array();
    		$register_data=array();
    		$local_data['phone_mob']=$phone_mob;
    		$local_data['address']=$address;
    		$passlen = strlen($password);
    		$user_name_len = strlen($user_name);
    		$local_data['is_factory']=0;
    		$local_data['role']=USER_CLIENT;
    		$register_data['consumer_name']=trim($_POST['consumer_name']);
    		$local_data['phone_tel']=trim($_POST['phone_tel']);
    		$local_data['is_qq']=trim($_POST['is_qq']);
    		$register_data['country']=trim($_POST['country']);
    		$local_data['activation']=0;
    		if ($_POST['region_id']){
    			$local_data['region_id']=trim($_POST['region_id']);
    			$local_data['region_name']=trim($_POST['region_name']);
    		}
//     		$store_arr=array();
//     		$store_arr['entity_store']=empty($_POST['entity_store'])?0:intval($_POST['entity_store']);
//     		$store_arr['entity_store_num']=empty($_POST['entity_store_num'])?0:intval($_POST['entity_store_num']);
//     		$store_arr['net_store']=empty($_POST['net_store'])?0:intval($_POST['net_store']);
//     		$store_arr['net_store_num']=empty($_POST['net_store_num'])?0:intval($_POST['net_store_num']);
//     		if (!empty($store_arr)){
//     			$register_data['store_scale']=serialize($store_arr);
//     		}
//     		$register_data['net_store_url']=trim($_POST['net_store_url']);
//     		$channel_arr=array();
//     		$channel_arr['merchant']=empty($_POST['merchant'])?0:intval($_POST['merchant']);
//     		$channel_arr['factory_channel']=empty($_POST['factory_channel'])?0:intval($_POST['factory_channel']);
//     		if (!empty($channel_arr)){
//     			$register_data['restock_channel']=serialize($channel_arr);
//     		}
    		$register_data['user_type']=trim($_POST['user_type']);
    		//$register_data['cooperate']=trim($_POST['cooperate']);
    		$default_merch=&m('member')->get(array('conditions'=>'default_merch=1 and activation=1','fields'=>'user_id,user_name,email'));
    		if (!empty($default_merch)){
    			$local_data['freight_id']=$default_merch['user_id'];
    		}else{
    			$local_data['freight_id']=0;
    		}
    		if ($user_name_len < 3 || $user_name_len > 25)
    		{
    			$this->show_warning('user_name_limit');
    
    			return;
    		}
    		if ($passlen < 6 || $passlen > 20)
    		{
    			$this->show_warning('password_length_error');
    
    			return;
    		}
    		if (!is_email($email))
    		{
    			$this->show_warning('email_error');
    
    			return;
    		}
    		if (!$address || strlen($address)>100){
    			$this->show_warning('address_error');
    			return;
    		}
    		
    		$ms =& ms(); //连接用户中心
    		$user_id = $ms->user->register($user_name, $password, $email,$local_data,$register_data,'consumer_info');
    
    		if (!$user_id)
    		{
    			$this->show_warning($ms->user->get_error());
    
    			return;
    		}
    		
    		//发送注册邮箱邮件
    		$user_info=& m('member')->get_info($user_id);
    		$mail = get_mail('user_on_send_activation', array('user' =>$user_info));
    		$this->_mailto($default_merch, addslashes($mail['subject']), addslashes($mail['message']));
    		//登录
    		$this->_do_login($user_id);
    		#TODO 可能还会发送欢迎邮件
    		header('location:index.php');
    	}
    }
    
    
    /**
     *    注册一个工厂
     *
     *    @author    Garbin
     *    @return    void
     */
    function factory_register()
    {
    	if ($this->visitor->has_login)
    	{
    		$this->show_warning('has_login');
    
    		return;
    	}
    	$upload_mod =& m('upload');
    	if (!IS_POST)
    	{
    		if (!empty($_GET['ret_url']))
    		{
    			$ret_url = trim($_GET['ret_url']);
    		}
    		else
    		{
    			if (isset($_SERVER['HTTP_REFERER']))
    			{
    				$ret_url = $_SERVER['HTTP_REFERER'];
    			}
    			else
    			{
    				$ret_url = SITE_URL . '/index.php';
    			}
    		}
    		$this->assign('ret_url', rawurlencode($ret_url));
    		//赋值session_id
    		$this->assign('phpsision', session_id());
    		//查询当前session_id下的上传图片
    		$img_file=$upload_mod->find(array(
    			'conditions'=>'session_id="'.session_id().'" and key_id=11233243'	
    		));
    		if ($img_file){
    			$this->assign('files',$img_file);
    		}
    		$this->_curlocal(LANG::get('user_register'));
    		$this->assign('page_title', Lang::get('user_register') . ' - ' . Conf::get('site_title'));
    		$fabric_type_mod=&m('fabric_type');
    		$fabric_type_list=$fabric_type_mod->find(array(
    				'conditions'=>'if_show=1',
    				'order'=>'fabric_type_id',
    				'limit'=>'15'
    		));
    		$this->assign('fabric_list',$fabric_type_list);
    		$region_mod=& m('region');
    		$this->assign('regions',$region_mod->get_options(0));
    		//     		if (Conf::get('captcha_status.register'))
    			//     		{
    			//     			$this->assign('captcha', 1);
    			//     		}
    
    		/* 导入jQuery的表单验证插件 */
    		//$this->import_resource('jquery.plugins/jquery.validate.js');
    		$this->display('factory_register.html');
    	}
    	else
    	{
    		//     		if (!$_POST['agree'])
    			//     		{
    			//     			$this->show_warning('agree_first');
    
    			//     			return;
    			//     		}
    		if ($_POST['password'] != $_POST['confirm_password'])
    		{
    			/* 两次输入的密码不一致 */
    			$this->show_warning('password_inconsistent');
    			return;
    		}
    
    		/* 注册并登陆 */
    		$user_name = trim($_POST['user_name']);
    		$password  = $_POST['password'];
    		$email     = trim($_POST['email']);
    		$phone_mob = trim($_POST['phone_mob']);
    		$address   = trim($_POST['address']);
    		$local_data=array();
    		$local_data['phone_mob']=$phone_mob;
    		$local_data['phone_tel']=trim($_POST['phone_tel']);
    		$local_data['address']=$address;
    		$passlen = strlen($password);
    		$user_name_len = strlen($user_name);
    		$local_data['is_factory']=1;
    		$local_data['role']=USER_FACTORY;
    		$local_data['region_id']=trim($_POST['region_id']);
    		$local_data['region_name']=trim($_POST['region_name']);
    		$local_data['is_qq']=trim($_POST['is_qq']);
    		$local_data['activation']=0;
    		$register_data=array();
    		$register_data['factory_name']=trim($_POST['factory_name']);
    		$register_data['factory_charge']=trim($_POST['factory_charge']);
//     		$register_data['charge_birthplace']=trim($_POST['charge_birthplace']);
    		$register_data['factory_person_num']=trim($_POST['factory_person_num']);
//     		$register_data['goods_quality']=empty($_POST['goods_quality'])?0:intval($_POST['goods_quality']);
//     		$fabric_type_id=array_filter($_POST['fabric_type_id']);
//     		$register_data['flat_car']=trim($_POST['flat_car']);
//     		$register_data['side_car']=trim($_POST['side_car']);
//     		$register_data['five_line_bus']=trim($_POST['five_line_bus']);
//     		$register_data['other_car']=trim($_POST['other_car']);
//     		$register_data['factory_equipment']=trim($_POST['factory_equipment']);
    		//$register_data['cooperate']=trim($_POST['cooperate']);
//     		if (!empty($fabric_type_id)){
//     			$register_data['fabric_type_id']=implode(',', $fabric_type_id);
//     		}
    		if ($user_name_len < 3 || $user_name_len > 25)
    		{
    			$this->show_warning('user_name_limit');
    
    			return;
    		}
    		if ($passlen < 6 || $passlen > 20)
    		{
    			$this->show_warning('password_length_error');
    
    			return;
    		}
    		
    		if (empty($_POST['region_name'])){
    			$this->show_warning('region_required');
    			
    			return;
    		}
    		
    		if (!is_email($email))
    		{
    			$this->show_warning('email_error');
    
    			return;
    		}
    		if (!$address || strlen($address)>100){
    			$this->show_warning('address_error');
    			return;
    		}
    
    		$ms =& ms(); //连接用户中心
    		$user_id = $ms->user->register($user_name, $password, $email,$local_data,$register_data,'factory_info');
    
    		if (!$user_id)
    		{
    			$this->show_warning($ms->user->get_error());
    
    			return;
    		}
    
    		$upfiles=$_POST['upfiles'];
    		
    		if(!empty($upfiles))
    		{
    			$factory_mod=&m('factory_info');
    			$factory_info=$factory_mod->get(array(
    				'conditions'=>'user_id='.$user_id	
    			));
    			if (!empty($factory_info)){
    				$upload_mod->edit("file_id ".db_create_in($upfiles),array("key_id"=>$factory_info['factory_id'],"session_id"=>session_id(),'file_type'=>BELONGS_FACTORY_IMAGE));
    			}
    		}
    		
    		//发送注册邮箱邮件
//     		$user_info=& m('member')->get_info($user_id);
//     		$mail = get_mail('user_on_send_activation', array('user' =>$user_info));
//     		$this->_mailto($user_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
    		//登录
    		$this->_do_login($user_id);
    		#TODO 可能还会发送欢迎邮件
    		header('location:index.php');
    	}
    }
    
    //供应商注册
    function merch_register(){
    	if ($this->visitor->has_login)
    	{
    		$this->show_warning('has_login');
    		return;
    	}
    	if (!IS_POST)
    	{
    		if (!empty($_GET['ret_url']))
    		{
    			$ret_url = trim($_GET['ret_url']);
    		}
    		else
    		{
    			if (isset($_SERVER['HTTP_REFERER']))
    			{
    				$ret_url = $_SERVER['HTTP_REFERER'];
    			}
    			else
    			{
    				$ret_url = SITE_URL . '/index.php';
    			}
    		}
    		$this->assign('ret_url', rawurlencode($ret_url));
    		$this->_curlocal(LANG::get('merchant_info'));
    		$this->assign('page_title', Lang::get('user_register') . ' - ' . Conf::get('site_title'));
    		$this->assign('fabric_types', $this->_get_options());
    		$this->display('register.merchant.html');
    	}
    	else
    	{
    		if ($_POST['password'] != $_POST['password2'])
    		{
    			/* 两次输入的密码不一致 */
    			$this->show_warning('password_inconsistent');
    			return;
    		}
    
    		/* 注册并登陆 */
    		$user_name = trim($_POST['user_name']);
    		$password  = $_POST['password'];
    		$email     = trim($_POST['email']);
    		$phone_mob = trim($_POST['phone_mob']);
    		$address   = trim($_POST['address']);
    		$local_data=array();
    		$local_data['phone_mob']=$phone_mob;
    		$local_data['phone_tel']=trim($_POST['phone_tel']);
    		$local_data['address']=$address;
    		$passlen = strlen($password);
    		$user_name_len = strlen($user_name);
    		$local_data['role']=USER_MERCHANT;
    		$local_data['is_qq']=trim($_POST['is_qq']);
    		$local_data['activation']=0;
    		$register_data=array();
    		$register_data['fabric_shop_name']=$user_name;
    		$register_data['type_id']=trim($_POST['type_id']);
    		//$register_data['description']=trim($_POST['description']);
    		$register_data['if_show']=0;
    		$fs_mod=&m('fabric_shop');
    		if ($user_name_len < 3 || $user_name_len > 25)
    		{
    			$this->show_warning('user_name_limit');
    
    			return;
    		}
    		if ($passlen < 6 || $passlen > 20)
    		{
    			$this->show_warning('password_length_error');
    
    			return;
    		}
    		
    		if ($email){
    			if (!is_email($email))
    			{
    				$this->show_warning('email_error');
    			
    				return;
    			}
    		}
    		
    		if (!$address || strlen($address)>100){
    			$this->show_warning('address_error');
    			return;
    		}
    
    		if (!$fs_mod->unique($fabric_name)) {
    			$this->show_warning('布行/档口已存在!');
    			return;
    		}
    		$ms =& ms(); //连接用户中心
    		$user_id = $ms->user->register($user_name, $password, $email,$local_data,$register_data,'fabric_shop');
    
    		if (!$user_id)
    		{
    			$this->show_warning($ms->user->get_error());
    
    			return;
    		}
    		
    		//发送注册邮箱邮件
//     		$user_info=& m('member')->get_info($user_id);
//     		if ($user_info['email']){
//     			$mail = get_mail('user_on_send_activation', array('user' =>$user_info));
//     			$this->_mailto($user_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
//     		}
    		//登录
    		$this->_do_login($user_id);
    		#TODO 可能还会发送欢迎邮件
    		header('location:index.php');
    	}
    }
    /**
     * 构造15位的随机字符串
     *
     * @return string | 生成的字符串
     */
    function _rand()
    {
    	$word = $this->generate_code();
    	return $word;
    }
    
    function generate_code($len = 15)
    {
    	$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    	for ($i = 0, $count = strlen($chars); $i < $count; $i++)
    	{
    	$arr[$i] = $chars[$i];
    	}
    
    	mt_srand((double) microtime() * 1000000);
    	shuffle($arr);
    	$code = substr(implode('', $arr), 5, $len);
    	return $code;
    }
    
    
    //激活邮箱
    function email_activation(){
    	$user_id=empty($_GET['id'])?0:intval($_GET['id']);
    	$act_code=empty($_GET['act_code'])?'':trim($_GET['act_code']);
    	if (!isset($user_id) || !isset($act_code) || !$act_code){
    		$this->show_warning("request_error",
    				'back_index', 'index.php');
    		return ;
    	}
    	$user_mod=& m('member');
    	$user_info=$user_mod->get(array(
    			'conditions'=>'user_id='.$user_id." and activation_code='{$act_code}' and activation_time>=".gmtime()
    	));
    	if (empty($user_info)){
    		$this->show_warning("link_dealine",'back_index','index.php');
    		return;
    	}
    	$edit_user=$user_mod->edit($user_id,array('activation'=>1));
    	if ($user_mod->has_error()){
    		$this->show_warning($user_mod->get_error());
    		return;
    	}
    	$this->show_message('activation_success',Lang::get('activation_email'),'index.php');
    }
    
	function home()
	{
		$order_mod =& m('order');
		$sample_mod =& m('sample');
		$ss_mod =& m('ss');
		$mod_cm=&m("company_manager");
		$mod_brand=&m("brand");
		$brand_ids=$mod_brand->find(array('conditions'=>"company_id in(select company_id from ($mod_cm->table) where uid={$this->visitor->get('user_id')})","fields"=>"brand_id"));
		
	    $user=$this->visitor->get();
        $this->assign('user',$user);

		if($user['role']==USER_MERCHANDISER_ADMIN)
		{
			$sample_approve_where=' AND brand_id'.db_create_in(array_keys($brand_ids));
			$eval_approve_where=' AND sample.brand_id'.db_create_in(array_keys($brand_ids));
		}
		$approve_num['sample_approve_num']=$sample_mod->getone("select count(*) from {$sample_mod->table} where status=".SAMPLE_STATUS_APPROVE.$sample_approve_where);
		$approve_num['order_approve_num']=$order_mod->getone("select count(*) from {$order_mod->table} where status in(".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_MANAGER.")".$sample_approve_where);
		$approve_num['order_ssapprove_num']=$ss_mod->getone("select count(*) from {$ss_mod->table} ss left join {$order_mod->table} o on ss.order_id=o.order_id where ss_status=".SS_STATUS_APPROVE.$sample_approve_where);
		$approve_num_quote_order=$order_mod->getone("select count(*) from {$order_mod->table} where quote_status=1 and quote_sn is not null".$sample_approve_where);
		$approve_num_quote_sample=$sample_mod->getone("select count(*) from {$sample_mod->table} where quote_status=1 and quote_sn is not null".$sample_approve_where);
		$approve_num['quote_approve_num']=$approve_num_quote_order+$approve_num_quote_sample;
		$this->assign('approve_num', $approve_num);
		
		if($user['role']==USER_FACTORY){
			$news_cate=NEWS_CATE_TZ_GC;
		}elseif ($user['role']==USER_CLIENT){
			$news_cate=NEWS_CATE_TZ_KH;
		}elseif (in_array($user['role'], array(USER_MANAGER,USER_MERCHANDISER_ADMIN,USER_OUTGOING,USER_FINANCE))){
			$this->assign('user_role',true);
		}elseif ($user['role']==USER_MERCHANT){
			$news_cate=NEWS_CATE_TZ_MERCH;
		}else{
			$news_cate=NEWS_CATE_TZ_YG;
		}
		//$news_cate=$user['role'] == USER_FACTORY ?NEWS_CATE_TZ_GC:NEWS_CATE_TZ_YG;
		$news_mod =& m('news');
		if (in_array($user['role'], array(USER_MANAGER,USER_MERCHANDISER_ADMIN,USER_OUTGOING,USER_FINANCE))){
			$conditions.='news.if_show = 1';
		}else{
			$conditions.='news.if_show = 1 AND FIND_IN_SET('.$news_cate.',news.cate_id)';
		}
		$news_list = $news_mod->find(array(
			'conditions' =>$conditions.' and cate_id not '.db_create_in(array(NEWS_CATE_GC,NEWS_CATE_YG,NEWS_CATE_CLENT_HELP)),
			//'join' => 'belongs_cate',
			'order' => 'update_date DESC',
			'limit' => '5'
		));
		$news = current($news_list);
		if (!empty($news_list)){
			foreach ($news_list as $key=>$value){
				$cate_arr_id=explode(',', $value['cate_id']);
				$news_list[$key]['cate_arr_id']=$cate_arr_id;
			}
		}
		/*$news['content'] = preg_replace("/\<[\s\w:;\-=,\'\"\/]*\>|[\n\r ]|&nbsp;/", '', $news['content']);
		$news['content'] = substr($news['content'], 0, preg_match('/[^\x00-\xff]/', substr($news['content'], 1098, 2)) ? 1100 : 1099) . '...';*/
		$this->assign('news', $news);
		$this->assign('news_list', $news_list);		
		
		//未完成生产板
		$producte_con="product_status!=".PRODUCT_STATUS_CREATE;
		if ($user['role']==USER_FACTORY){
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$producte_con .=" and factory_id=".$user['factory_id'];
		}elseif ($user['role']==USER_MERCHANDISER){
			$producte_con .=" and merchandiser_id=".$user['user_id'];
		}elseif ($user['role']==USER_MERCHANDISER_ADMIN){
			$producte_con .=" and 1=1".$sample_approve_where;
		}elseif ($user['role']==USER_MANAGER){
			$producte_con .=" and 1=1";
		}
		$producte_num=$order_mod->getone("select count(*) from {$order_mod->table} where ".$producte_con);
		$this->assign('producte_num',$producte_num);
		//待审批的色卡
		$colorcard_mod=&m('color_card');
		if (in_array($user['role'], array(USER_MERCHANDISER,USER_FACTORY))){
			$approve_color=$colorcard_mod->getone("select count(*) from {$colorcard_mod->table} where color_status=0 and user_id=".$user['user_id']);
		}elseif (in_array($user['role'], array(USER_MANAGER,USER_CIVILIAN,USER_MERCHANDISER_ADMIN))){
			$approve_color=$colorcard_mod->getone("select count(*) from {$colorcard_mod->table} where color_status=0");
		}
		$this->assign('approve_color',$approve_color);
		$sample_conditions="";
		$search_status="";
		if($user['role']==USER_FACTORY)
		{
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$search_status="5,51";
			$sample_conditions='ref_sample_style != 3 AND factory_id = ' . $this->visitor->get('factory_id') . " AND status in({$search_status}) ";
		}
		elseif(in_array($user['role'], array(USER_MERCHANDISER_ADMIN)))
		{
			$search_status="0,11,5,51,6";
			$sample_conditions="ref_sample_style != 3  AND status in({$search_status}) AND brand_id".db_create_in(array_keys($brand_ids));
		}elseif(in_array($user['role'], array(USER_MANAGER))){
			$search_status="0,11,5,51,6";
			$sample_conditions="ref_sample_style != 3  AND status in({$search_status})";
		}elseif ($user['role']==USER_CLIENT){
			$search_status="0,11,5,51,6";
			$sample_conditions='ref_sample_style != 3 AND buyer_id = ' . $this->visitor->get('user_id') . " AND status in({$search_status})" ;
		}
		else
		{
			$search_status="0,11,5,51,6";
			$sample_conditions='ref_sample_style != 3 AND merchandiser_id = ' . $this->visitor->get('user_id') . " AND status in({$search_status})" ;
		}
		
		$sample = count($sample_mod->find(array(
			'conditions' => $sample_conditions
		)));
		$this->assign('sample', $sample);
		$this->assign('search_status', $search_status);

		$order_conditions="";
		if($user['role']==USER_FACTORY)
		{
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$order_conditions=' factory_id = ' . $this->visitor->get('factory_id') . ' AND status in(1,8,81,82,9)';
		}
		elseif(in_array($user['role'], array(USER_MERCHANDISER_ADMIN)))
		{
			$order_conditions=' status in(1,8,81,82,9) AND brand_id'.db_create_in(array_keys($brand_ids));
		}elseif (in_array($user['role'], array(USER_MANAGER))){
			$order_conditions=' status in(1,8,81,82,9)';
		}elseif ($user['role']==USER_CLIENT){
			$order_conditions ='buyer_id = ' . $this->visitor->get('user_id') . ' AND status in(1,8,81,82,9)';
		}
		else
		{
			$order_conditions ='merchandiser_id = ' . $this->visitor->get('user_id') . ' AND status in(1,8,81,82,9)';
		}
		$order = count($order_mod->find(array(
			'conditions' => $order_conditions
		)));
		
		$this->assign('order', $order);
		
		//财务待审批订单
		if($user['role']==USER_FINANCE){
			$approve_conditions = "status in(".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_FINANCE.")";
			$approve = count($order_mod->find(array('conditions'=>$approve_conditions)));
			$this->assign("approve",$approve);
			$discount_con=" dis_status=".ORDER_DIS_STATUS_APPROVE_FINANCE;
			$approve_discount=count($order_mod->find(array('conditions'=>$discount_con)));
			$this->assign('approve_discount',$approve_discount);
		}
		
		//客户经理
		if($this->visitor->get('role')==USER_CLIENT){
			$member_mod=&m('member');
			$user_info=$member_mod->get($this->visitor->get('user_id'));
			if ($user_info['freight_id']){
    			$merch=$member_mod->get(array(
    				'conditions'=>'user_id='.$user_info['freight_id'].' and role='.USER_MERCHANDISER
    			));
    			$this->assign('merch',$merch);
    		}
		}
		
		$merch_mod=&m('merchant_fabric');
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('order_count', '1');
			$gb_mod=&m('guestbook');
			$reply_num=$gb_mod->getone("select count(*) from {$gb_mod->table} where reply_time=0");
			$this->assign('reply_num',$reply_num);
			
			$eval_num=0;
			$eval=$sample_mod->find(array(
				'conditions' => 'sample.status '.db_create_in(array(SAMPLE_STATUS_SEND_SAMPLE,SAMPLE_STATUS_STOCK)).' and evaluate_time is null',
				'join' => 'belongs_brand,belongs_merchandiser,belongs_style,belongs_factory,has_evaluate',
			));
			if (!empty($eval)){
				$eval_num=count($eval);
			}
			$this->assign('eval_num',$eval_num);
			
			//待审批需求
			$merchants=$merch_mod->find(array(
				'conditions'=>'demand_status=1'	
			));
			if (!empty($merchants)){
				$approve_fabric=count($merchants);
			}
			$this->assign('approve_fabric',$approve_fabric);
		}
		
		if ($this->visitor->get('role') == USER_MERCHANDISER_ADMIN) {
			$eval_num=0;
			$eval=$sample_mod->find(array(
					'conditions' => 'sample.status '.db_create_in(array(SAMPLE_STATUS_SEND_SAMPLE,SAMPLE_STATUS_STOCK)).' and evaluate_time is null'.$eval_approve_where,
					'join' => 'belongs_brand,belongs_merchandiser,belongs_style,belongs_factory,has_evaluate',
			));
			if (!empty($eval)){
				$eval_num=count($eval);
			}
			$this->assign('eval_num',$eval_num);
			
			//待审批需求
			$all_user=$this->child_user();
			$merchants=$merch_mod->find(array(
					'conditions'=>'demand_status=1 and user_id '.db_create_in($all_user)
			));
			if (!empty($merchants)){
				$approve_fabric=count($merchants);
			}
			$this->assign('approve_fabric',$approve_fabric);
		}
		
		if ($this->visitor->get('role') == USER_MERCHANDISER){
			$eval_num=0;
			$eval=$sample_mod->find(array(
					'conditions' => 'sample.status '.db_create_in(array(SAMPLE_STATUS_SEND_SAMPLE,SAMPLE_STATUS_STOCK)).' and evaluate_time is null and merchandiser_id='.$this->visitor->get('user_id'),
					'join' => 'belongs_brand,belongs_merchandiser,belongs_style,belongs_factory,has_evaluate',
			));
			if (!empty($eval)){
				$eval_num=count($eval);
			}
			$this->assign('eval_num',$eval_num);
		}
		
		//工厂待报价
		if ($this->visitor->get('role')==USER_FACTORY){
			$factory_id=$user['factory_id'];
			$sample_quote=$sample_mod->find(array(
				'conditions'=>"quote_status=2 and quote_sn is not null and FIND_IN_SET({$factory_id},factory_quote_id)",
				'fields'=>'quote_sn'	
			));
			$order_quote=$order_mod->find(array(
					'conditions'=>"quote_status=2 and quote_sn is not null and FIND_IN_SET({$factory_id},factory_quote_id)",
					'fields'=>'quote_sn'
			));
			$quote_mod=&m('quote');
			if (!empty($sample_quote)){
				foreach ($sample_quote as $s_k=>$s_v){
					$s_id=$s_v['sample_id'];
					$quote_info=$quote_mod->get(array(
							'conditions'=>'sample_id='.$s_id.' and factory_id='.$factory_id
					));
					if (!empty($quote_info)){
						unset($sample_quote[$s_k]);
					}
				}
				if (!empty($sample_quote)){
					$sq_num=count($sample_quote);
				}
			}
			if (!empty($order_quote)){
				foreach ($order_quote as $o_k=>$o_v){
					$o_id=$o_v['order_id'];
					$q_info=$quote_mod->get(array(
							'conditions'=>'order_id='.$o_id.' and factory_id='.$factory_id
					));
					if (!empty($q_info)){
						unset($order_quote[$o_k]);
					}
				}
				if (!empty($order_quote)){
					$oq_num=count($order_quote);
				}
			}
			$quote_num=$sq_num+$oq_num;
			$this->assign('quote_num',$quote_num);
		}
		
		$search_status_brand="0,11,5,51,6";
		$this->assign("search_status_brand",$search_status_brand);

			/* 统计信息 */
			$brand_mod =& m('brand');
			$brands = $brand_mod->find(array(
				'conditions' => "1=1 ",
				'order' => 'brand_name ASC'
			));
			foreach ($brands as $key => $brand) {
				$samples = $sample_mod->find(array(
					'conditions' => "brand_id = {$brand[brand_id]} AND status in({$search_status_brand}) ",
				));
				if (!$samples) {
					unset($brands[$key]);
					continue;
				}
				$brands[$key]['sample'] = count($samples);
				$count_create = $count_send_factory = $count_send_sample = 0;
				foreach ($samples as $sample) {
					if ($sample['status'] == SAMPLE_STATUS_CREATE) {
						$count_create += 1;
					}
					if ($sample['status'] == SAMPLE_STATUS_SEND_FACTORY) {
						$count_send_factory += 1;
					}
					if ($sample['status'] == SAMPLE_STATUS_SEND_SAMPLE) {
						$count_send_sample += 1;
					}
				}
				$brands[$key]['create'] = $count_create;
				$brands[$key]['send_factory'] = $count_send_factory;
				$brands[$key]['send_sample'] = $count_send_sample;
			}
			$temp = array();
			foreach ($brands as $key => $val) {
				foreach ($brands as $k => $v) {
					if ($brands[$key]['sample'] > $brands[$k]['sample']) {
						$temp = $brands[$key];
						$brands[$key] = $brands[$k];
						$brands[$k] = $temp;
					}
				}
			}
			$this->assign('brands', $brands);
			
			$factory_mod =& m('factory_info');
			$factorys = $factory_mod->find(array(
				'order' => 'factory_name asc',
			));
			$sample_status="0,5,11,51";
			$this->assign('sample_status',$sample_status);
			$now_date=date('Y-m',gmtime());
			foreach ($factorys as $key => $factory) {
				$samples = $sample_mod->find(array(
					'conditions' => "factory_id = {$factory[factory_id]} AND status not ".db_create_in(array(SAMPLE_STATUS_DELETE))." and send_sample_date >= " . strtotime($now_date.'-1') . " AND send_sample_date <= " . strtotime($now_date.'-31')
				));
				$all_samples = $sample_mod->find(array(
					'conditions' => "factory_id = {$factory[factory_id]} AND status ".db_create_in(array(SAMPLE_STATUS_SEND_FACTORY,SAMPLE_STATUS_FACTORY_SUBMIT))
				));
				if (!$all_samples) {
					unset($factorys[$key]);
					continue;
				}
				$count_sample = count($samples);
				$factorys[$key]['sample'] = count($all_samples);
				$average = 0;
				$count_sample_made_days = 0;
				foreach ($samples as $sample) {
					if (!$sample['to_factory_date']) continue;
					if (!$sample['send_sample_date']) {
						$sample['send_sample_date'] = time();
					}
					$sample_made_days = round(($sample['send_sample_date'] - $sample['to_factory_date']) / 60 / 60 / 24);
					$count_sample_made_days += $sample_made_days;
				}
				$average = intval($count_sample_made_days / $count_sample);
				$factorys[$key]['average'] = $average;
			}
			foreach ($factorys as $key => $val) {
				foreach ($factorys as $k => $v) {
					if ($factorys[$key]['sample'] > $factorys[$k]['sample']) {
						$temp = $factorys[$key];
						$factorys[$key] = $factorys[$k];
						$factorys[$k] = $temp;
					}
				}
			}
			$this->assign('factorys', $factorys);
		
		/*$sourcing_mod =& m('sourcing');
		$sourcing = count($sourcing_mod->find(array(
			'conditions' => 'sourcing_assistant_id = ' . $this->visitor->get('user_id') . ' AND status < 4',
		)));
		$this->assign('sourcing', $sourcing);*/
		
		$this->display('home.html');
		$this->_curlocal(Lang::get('index'));
	}
	
	function reset_factory()
	{
		$id = intval($_GET['id']);
		if (!$id) {
			$this->_json_msg('工厂不存在');
		}
		$factory_mod =& m('factory');
		$factory = $factory_mod->get_info($id);
		if (!$factory) {
			$this->_json_msg('工厂不存在');
		}
		$sample_mod =& m('sample');
		$samples = $sample_mod->find(array(
			'conditions' => "factory_id = {$id} AND status < " . SAMPLE_STATUS_STOCK
		));
		$count_samples = count($samples);
		$average = 0;
		$count_sample_made_days = 0;
		$no_to_factory_date = 0;
		$no_send_sample_date = 0;
		foreach ($samples as $sample) {
			if (!$sample['to_factory_date']) {
				$no_to_factory_date += 1;
				continue;
			}
			if (!$sample['send_sample_date']) {
				$sample['send_sample_date'] = time();
				$no_send_sample_date += 1;
			} else {
				$reset = true;
			}
			$sample_made_days = intval(($sample['send_sample_date'] - $sample['to_factory_date']) / 60 / 60 / 24) + 1;
			$count_sample_made_days += $sample_made_days;
			if ($reset) {
				$sample_mod->edit($sample['sample_id'], array('sample_made_days'=>$sample_made_days));
			}
		}
		$average = intval($count_sample_made_days / $count_samples);
		$return = array(
			'sample' => $count_samples,
			'average' => $average,
			'no_to_factory_date' => $no_to_factory_date,
			'no_send_sample_date' => $no_send_sample_date,
		);
		$this->_json_msg('', true, $return);
	}
	
	function _json_msg($msg, $done = false, $ret = array())
	{
		$json = array(
			'msg' => $msg,
			'done' => $done,
			'ret' => $ret
		);
		
		echo ecm_json_encode($json);
		exit;
	}
    /**
     *    �޸�����
     *
     *    @author    Hyber
     *    @usage    none
     */
    function password(){
        $user_id = $this->visitor->get('user_id');
        if (!IS_POST)
        {
            /* ��ǰλ�� */
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));
            $this->display('member.password.html');
            $this->_curlocal(LANG::get('edit_password'));
        }
        else
        {
            /* �����������������ͬ */
            $orig_password      = $_POST['orig_password'];
            $new_password       = $_POST['new_password'];
            $confirm_password   = $_POST['confirm_password'];
            if ($new_password != $confirm_password)
            {
                $this->show_warning('twice_pass_not_match');

                return;
            }
            if (!$new_password)
            {
                $this->show_warning('no_new_pass');

                return;
            }
            $passlen = strlen($new_password);
            if ($passlen < 6 || $passlen > 20)
            {
                $this->show_warning('password_length_error');

                return;
            }

            /* �޸����� */
            $ms =& ms();    //�����û�ϵͳ
            $result = $ms->user->edit($this->visitor->get('user_id'), $orig_password, array(
                'password'  => $new_password
            ));
            if (!$result)
            {
                /* �޸Ĳ��ɹ�����ʾԭ�� */
                $this->show_warning($ms->user->get_error());

                return;
            }

            $this->show_message('edit_password_successed');
        }
    }
	
	function order_count()
	{
		$factory_id = isset($_GET['factory_id']) ? intval($_GET['factory_id']) : 0;
		$q_id=isset($_GET['qc_id']) ? intval($_GET['qc_id']) : 0;
		$status = intval($_GET['status']);
		if (!$status){
			$conditions=" and status!=".ORDER_STATUS_NO_CANCEL;
		}
		$year = intval($_GET['year']);
		$factory_mod =& m('factory_info');
		$order_mod =& m('order');
		$user=$this->visitor->get();
		if ($user['role'] == USER_MERCHANDISER_ADMIN){
			$this->assign('merch_admin',true);
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions.=" and o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}
		if ($user['role'] == USER_OUTGOING){
			$this->assign('qc_admin',true);
		}
		if ($user['role'] == USER_MANAGER){
			$this->assign('is_manager',true);
		}
		if ($factory_id || $q_id) {
			if ($q_id){
				$member_mod=&m('member');
				$qc_mod=&m('qcfactory');
				$factory = $member_mod->get_info($q_id);
				$qc_factory=$qc_mod->find(array(
					'conditions'=>'user_id='.$q_id	
				));
				
				if (!empty($qc_factory)){
					foreach ($qc_factory as $value){
						$factory_arr[]=$value['factory_id'];
					}
				}
				$orders = $order_mod->find(array(
						'conditions' => 'factory_id' . db_create_in($factory_arr) . ($status ? ' AND status = ' . $status : '') . ' AND release_date >= ' . strtotime($year . '-1-1') . ' AND release_date <= ' . strtotime($year . '-12-31').$conditions,
						'order' => 'release_date ASC'
				));
				$this->assign('is_qc',true);
			}else{
				$factory = $factory_mod->get_info($factory_id);
				$orders = $order_mod->find(array(
						'conditions' => 'factory_id = ' . $factory_id . ($status ? ' AND status = ' . $status : '') . ' AND release_date >= ' . strtotime($year . '-1-1') . ' AND release_date <= ' . strtotime($year . '-12-31').$conditions,
						'order' => 'release_date ASC'
				));
			}
			foreach ($orders as $key => $val) {
				$months = array(1=>'',2=>'',3=>'',4=>'',5=>'',6=>'',7=>'',8=>'',9=>'',10=>'',11=>'',12=>'');
				if ($val['release_date']) {
					$month = intval(date('m', $val['release_date']));
					$months[$month] = date('m月d日', $val['release_date']);
				}
				$orders[$key]['months'] = $months;
			}
			$factory['orders'] = $orders;
			$this->assign('factory', $factory);
			$this->display('order_count.html');
			return;
		}
		$merchandiser = intval($_GET['merchandiser']);
		$userqc = intval($_GET['userqc']);
		$years = array();
		$this_year = $year ? $year : date('Y');
		for($i = $this_year - 10; $i <= $this_year+1; $i++) {
			$years[$i] = $i;
		}
		$this->assign('years', $years);
		$this->assign('this_year', $this_year);
		if (!$merchandiser && !$userqc) {
			$factorys = $factory_mod->find(array(
				'join'=>'belongs_factory_member',
				'conditions' => 'if_show = 1',
				'order' => 'factory_name ASC'
			));
			foreach ($factorys as $key => $val) {
				$orders = $order_mod->find(array(
					'conditions' => 'factory_id = ' . $val['factory_id'] . ($status ? ' AND status = ' . $status : '') . ' AND release_date >= ' . strtotime($this_year . '-1-1') . ' AND release_date <= ' . strtotime($this_year . '-12-31').$conditions,
				));
				$factorys[$key]['order_count'] = count($orders);
				$quantity = array(0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,9=>0,10=>0,11=>0,12=>0);
				foreach ($orders as $k => $v) {
					$quantity[0] += $v['quantity'];
					switch (intval(date('m', $v['release_date']))) {
						case 1 :
							$quantity[1] += $v['quantity'];
							break;
						case 2 :
							$quantity[2] += $v['quantity'];
							break;
						case 3 :
							$quantity[3] += $v['quantity'];
							break;
						case 4 :
							$quantity[4] += $v['quantity'];
							break;
						case 5 :
							$quantity[5] += $v['quantity'];
							break;
						case 6 :
							$quantity[6] += $v['quantity'];
							break;
						case 7 :
							$quantity[7] += $v['quantity'];
							break;
						case 8 :
							$quantity[8] += $v['quantity'];
							break;
						case 9 :
							$quantity[9] += $v['quantity'];
							break;
						case 10 :
							$quantity[10] += $v['quantity'];
							break;
						case 11 :
							$quantity[11] += $v['quantity'];
							break;
						case 12 :
							$quantity[12] += $v['quantity'];
							break;
					}
				}
				$factorys[$key]['quantitys'] = $quantity;
			}
			$this->assign('factorys', $factorys);
		}elseif (!$merchandiser && $userqc){
			$member_mod=&m('member');
			$qc_mod=&m('qcfactory');
			$qc_list = $member_mod->find(array(
					'conditions' => 'if_show = 1 and role'.db_create_in(array(USER_QC,USER_OUTGOING)),
					'order' => 'user_name ASC'
			));
			foreach ($qc_list as $key => $val) {
				$qc_arr=array();
				$qc_id=$val['user_id'];
				$qc_factory_arr=$qc_mod->find(array(
						'conditions'=>'user_id='.$qc_id
				));
				if (!empty($qc_factory_arr)){
					foreach ($qc_factory_arr as $res){
						$qc_arr[]=$res['factory_id'];
					}
				}
				$orders = $order_mod->find(array(
						'conditions' => 'factory_id' . db_create_in($qc_arr) . ($status ? ' AND status = ' . $status : '') . ' AND release_date >= ' . strtotime($this_year . '-1-1') . ' AND release_date <= ' . strtotime($this_year . '-12-31').$conditions,
				));
				$qc_list[$key]['order_count'] = count($orders);
				$quantity = array(0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,9=>0,10=>0,11=>0,12=>0);
				foreach ($orders as $k => $v) {
					$quantity[0] += $v['quantity'];
					switch (intval(date('m', $v['release_date']))) {
					case 1 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}						
							$quantity[1] += $num;
							break;
						case 2 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[2] += $num;
							break;
						case 3 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[3] += $num;
							break;
						case 4 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[4] += $num;
							break;
						case 5 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[5] += $num;
							break;
						case 6 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[6] += $num;
							break;
						case 7 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[7] += $num;
							break;
						case 8 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[8] += $num;
							break;
						case 9 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[9] += $num;
							break;
						case 10 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[10] += $num;
							break;
						case 11 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[11] += $num;
							break;
						case 12 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[12] += $num;
							break;
					}
				}
				$qc_list[$key]['quantitys'] = $quantity;
			}
			$this->assign('qc_list', $qc_list);
			$this->assign('userqc',$userqc);
		}else {
			if($user['role']==USER_MANAGER)
			{
				$mod_brand=&m("brand");
				$brand_ids=$mod_brand->find(array('conditions'=>"if_show=1","fields"=>"brand_id"));
				$brands=array_keys($brand_ids);
			}
			if($user['role']==USER_MERCHANDISER_ADMIN)
			{
				$mod_cm=&m("company_manager");
				$mod_brand=&m("brand");
				$brand_ids=$mod_brand->find(array('conditions'=>"company_id in(select company_id from ($mod_cm->table) where uid={$this->visitor->get('user_id')})","fields"=>"brand_id"));
				$brands=array_keys($brand_ids);
			}
			$user_mod =& m('member');
			$buyer_list=$user_mod->find(array(
				'conditions'=>'role='.USER_CLIENT.' and activation=1'	
			));
			$flag=0;
			if (!empty($buyer_list)){
				foreach ($buyer_list as $j=>$row){
					$brand_arr_id=explode(',', $row['brand_arr_id']);
					$brand_arr=array_merge($brand_arr_id,$brands);
					$brand_arr_ids=array_count_values($brand_arr);
					if (!empty($brand_arr_ids)){
						foreach ($brand_arr_ids as $i=>$r){
							if ($brand_arr_ids[$i]>1){
								$flag=1;
								break;
							}else{
								$flag=0;
							}
						}
					}
					if ($flag){
						$freight_id[]=$row['freight_id'];
					}
				}
			}
			$merchandisers = $user_mod->find(array(
				'conditions' => 'role = ' . USER_MERCHANDISER . ' AND if_show = 1 and user_id'.db_create_in(array_unique($freight_id)),
				'order' => 'user_name ASC',
			));
			foreach ($merchandisers as $key => $val) {
				$orders = $order_mod->find(array(
					'conditions' => 'merchandiser_id = ' . $val['user_id'] . ($status ? ' AND status = ' . $status : '') . ' AND order_create_date >= ' . strtotime($this_year . '-1-1') . ' AND order_create_date <= ' . strtotime($this_year . '-12-31'),
				));
				$merchandisers[$key]['order_count'] = count($orders);
				$quantity = array(0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,9=>0,10=>0,11=>0,12=>0,);
				$num_arr=array();
				foreach ($orders as $k => $v) {
					$quantity[0] += $v['quantity'];
					switch (intval(date('m', $v['order_create_date']))) {
						case 1 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}						
							$quantity[1] += $num;
							break;
						case 2 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[2] += $num;
							break;
						case 3 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[3] += $num;
							break;
						case 4 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[4] += $num;
							break;
						case 5 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[5] += $num;
							break;
						case 6 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[6] += $num;
							break;
						case 7 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[7] += $num;
							break;
						case 8 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[8] += $num;
							break;
						case 9 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[9] += $num;
							break;
						case 10 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[10] += $num;
							break;
						case 11 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[11] += $num;
							break;
						case 12 :
							$num=0;
							if ($v['style_sn']){
								if (!in_array($v['style_sn'], $num_arr)){
									$num_arr=array_push($num_arr, $v['style_sn']);
									$num=1;
								}
							}
							$quantity[12] += $num;
							break;
					}
				}
				$merchandisers[$key]['quantitys'] = $quantity;
			}
			$this->assign('merchandisers', $merchandisers);
			$this->assign('merchandiser',$merchandiser);
			$this->assign('status',$status?$status:-1);
		}
		$this->assign('user',$user);
		$this->display('order_count.html');
	}
	
	/*function data_to_new_virsion()
	{
		$sourcitem_mod =& m('sourcingitem');
		$fabricinfo_mod =& m('fabric_info');
		$file_mod =& m('upload');
		if (!isset($_GET['ajax'])) {
			$this->check_powers(USER_ADMIN);
			$list = $sourcitem_mod->find(array(
				'conditions' => 'sourcing_list.type = ' . SOURCING_LIST_TYPE_SAMPLE . ' OR sourcing_list.type = ' . SOURCING_LIST_TYPE_FABRIC,
				'join' => 'belongs_sourcing',
				'count'=>true,
			));
			$list_file = $file_mod->find(array('conditions'=>'file_type = ' . BELONGS_SOURCING_LIST, 'count'=>true));
			$this->assign('count', $sourcitem_mod->getCount());
			$this->assign('count_file', $file_mod->getCount());
			$this->display('data_to_new_virsion.html');
		} else {
			if (!$this->check_powers(USER_ADMIN, false)) {
				echo ecm_json_encode(array(
					'done'=> false,
					'msg' => '您没有权限使用该功能！',
				));
				return;
			}
			$page = $this->_get_page(20);
			if ($_GET['type'] == 'sourcing') {
				$list = $sourcitem_mod->find(array(
					'conditions' => 'sourcing_list.type = ' . SOURCING_LIST_TYPE_SAMPLE . ' OR sourcing_list.type = ' . SOURCING_LIST_TYPE_FABRIC,
					'order' => 'item_id',
					'limit' => $page['limit'],
					'join' => 'belongs_sourcing',
					'count' => true,
				));
				if (!$list) {
					echo ecm_json_encode(array(
						'done' => true,
						'finished' => true,
						'type' => 'sourcing',
					));
					return;
				}
				foreach ($list as $key => $val) {
					if (!$fabricinfo_mod->find(array('conditions'=>'sample_id = '.$val['key_id']))) {
						$fabricinfo_mod->add(array('sample_id'=>$val['key_id'],'description'=>$val['sourcing_info'].' '.$val['fabric_info'],'fabric_shop_id'=>$val['fabric_shop_id']));
					}
				}
				echo ecm_json_encode(array(
					'done' => true,
					'finished' => false
				));
			} else {
				$file_mod->edit('file_type = '. BELONGS_SOURCING_LIST, array('file_type'=>BELONGS_COLORCARD));
				echo ecm_json_encode(array(
					'done' => true,
					'finished' => true,
					'type' => 'file'
				));
			}
		}
	}
	
	function new_sample_status()
	{
		if (!$this->check_powers(USER_ADMIN, false)) {
			echo ecm_json_encode(array(
				'done'=> false,
				'msg' => '您没有权限使用该功能！',
			));
			return;
		}
		$sample_mod =& m('sample');
		$sample_mod->edit('status in (1,2,3,4)', array('status'=>SAMPLE_STATUS_CREATE));
		if ($sample_mod->get_error()) {
			echo ecm_json_encode(array(
				'done' => false,
				'msg' => $sample_mod->get_error(),
			));
		}
		echo ecm_json_encode(array(
			'done' => true,
			'msg' => '样板状态更新成功！',
		));
	}
	
	function update_file_data()
	{
		if (!isset($_GET['page'])) {
?>
<script language="javascript" type="text/javascript" src="template/style/js/jquery-1.2.6.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
	$('#submit').click(function() {
		$(this).attr('disabled', true);
		update(1);
	});
});
function update(page) {
	$('#message').html('正在更新' + page + '，请稍后...');
	$.getJSON('index.php?app=default&act=update_file_data&page=' + page, function(json) {
		if (json.done) {
			update(page + 1);
		} else {
			$('#message').html('更新完毕！');
		}
	});
}
</script>
<form method="post" action="index.php?app=default&act=update_file_data">
<input type="button" value="开始" id="submit" />
</form>
<div id="message"></div>
<?php
		} else {
			$sourcing_mod =& m('sourcing');
			$page = $this->_get_page(50);
			$sourcing_list = $sourcing_mod->find(array(
				'conditions' => 'type = 1 or type = 3',
				'join' => 'belongs_sample',
				'limit' => $page['limit'],
			));
			if ($sourcing_list) {
				$file_mod =& m('upload');
				foreach ($sourcing_list as $key => $val) {
					$file_mod->edit('file_type = 13 and key_id = ' . $val['list_id'], array('key_id'=>$val['sample_id']));
				}
				echo ecm_json_encode(array('done'=>true));
			} else {
				echo ecm_json_encode(array('done'=>false));
			}
		}
	}*/
	
	function down()
	{

		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		
		header('Content-type: text/html; charset=gb2312');
		if (!$id) {
			echo '文件不存在！';
			return;
		}
		
		$upload_mod =& m('upload');
		$file = $upload_mod->get_info($id);
		if (!$file) {
			echo '文件不存在！';
			return;
		}
		
		$down_acc=true;
		$user=$this->visitor->get();
		$sample_mod=&m("sample");
		$order_mod=&m("order");
		if($user['is_factory']==1)
		{
			$belongs=$file['file_type'];
			
			if (in_array($belongs,array(BELONGS_SAMPLE,BELONGS_SAMPLE_FILESIZE,BELONGS_SAMPLE_CUSTOMER_REVIEWS,BELONGS_SAMPLE_MAKEPANEL,BELONGS_FACTORY,BELONGS_CONSUMER_REVIEWS,BELONGS_CONSUMER_REMARK))) {
				$sample_info=$sample_mod->get("sample_id={$file['key_id']}");
				
				if(empty($sample_info) || $sample_info['factory_id']!=$user['factory_id'])
				{
					
					$down_acc=false;
				}
			
			} elseif (in_array($belongs,array(BELONGS_ORDER,BELONGS_PIGAI,BELONGS_HETONG))) {
				$order_info=$order_mod->get("order_id={$file['key_id']}");
				if(empty($order_info) || $order_info['factory_id']!=$user['factory_id'])
				{
					$down_acc=false;
				}
			} 
			 elseif (in_array($belongs,array(BELONGS_COLORCARD_CC))) {
					$down_acc=true;
			} 
			else{
				$down_acc=true;
			}

		}
		
		if(!$down_acc)
		{
			echo '无权限下载此文件！';
			return;
		}
		
		$sn=(time()+10050)*2;
		header("location:downfile.php?sn={$sn}&id=" . $id);
		
	}
	
	//获取跟单主管下的用户
	function child_user(){
		$user_arr=array();
		$mod_cm=&m("company_manager");
		$mod_brand=&m("brand");
		$brand_id=$mod_brand->find(array('conditions'=>"company_id in(select company_id from ($mod_cm->table) where uid={$this->visitor->get('user_id')})","fields"=>"brand_id"));
		$brands=array_keys($brand_id);
		$user_mod =& m('member');
		$buyer_list=$user_mod->find(array(
				'conditions'=>'role='.USER_CLIENT.' and activation=1'
		));
		$flag=0;
		if (!empty($buyer_list)){
			foreach ($buyer_list as $j=>$row){
				$brand_arr_id=explode(',', $row['brand_arr_id']);
				$brand_arr=array_merge($brand_arr_id,$brands);
				$brand_arr_ids=array_count_values($brand_arr);
				if (!empty($brand_arr_ids)){
					foreach ($brand_arr_ids as $i=>$r){
						if ($brand_arr_ids[$i]>1){
							$flag=1;
							break;
						}else{
							$flag=0;
						}
					}
				}
				if ($flag){
					$freight_id[]=$row['freight_id'];
				}
			}
		}
		if (!empty($freight_id)){
			$member_list=$user_mod->find(array(
					'conditions'=>'role='.USER_CLIENT.' and activation=1 and freight_id'.db_create_in($freight_id)
			));
			if (!empty($member_list)){
				foreach ($member_list as $val){
					$member_arr[]=$val['user_id'];
				}
			}
		}
		$user_arr=array_merge($freight_id,$member_arr);
		return $user_arr;
	}
	
	/* 构造并返回树 */
	function &_tree($types)
	{
		import('tree.lib');
		$tree = new Tree();
		$tree->setTree($types, 'fabric_type_id', 'parent_id', 'fabric_type_name');
		return $tree;
	}
	
	/* 取得可以作为上级的类型数据 */
	function _get_options($except = NULL)
	{
		$ft_mod=&m('fabric_type');
		$types = $ft_mod->get_list();
		$tree =& $this->_tree($types);
		return $tree->getOptions(MAX_LAYER - 1, 0, $except);
	}
}

?>
